package com.dnndo.system.transApi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class TransApi {
    private static final String TRANS_API_HOST = "https://fanyi-api.baidu.com/api/trans/vip/translate";

    private final String appid;
    private final String securityKey;

    public TransApi(@Value("${baidu.translate.appid}") String appid,
                    @Value("${baidu.translate.securityKey}") String securityKey) {
        this.appid = appid;
        this.securityKey = securityKey;
    }
    public JSONObject getTransResult(String query, String from, String to) {
        Map<String, String> params = buildParams(query, from, to);
        String out = HttpGet.get(TRANS_API_HOST, params);

        // 解析JSON
        JSONObject json = JSON.parseObject(out);

        // 创建最终返回的JSON对象
        JSONObject finalResult = new JSONObject();
        finalResult.put("from", json.getString("from"));
        finalResult.put("to", json.getString("to"));
        finalResult.put("trans_result", json.getJSONArray("trans_result"));

        return finalResult;
    }
    private Map<String, String> buildParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);

        params.put("appid", appid);
        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);
        // 签名
        String src = appid + query + salt + securityKey; // 加密前的原文
        params.put("sign", MD5.md5(src));

        return params;
    }

}
